'use strict';

const Service = require('egg').Service;
class MovieService extends Service {
  async find(m) {
    const db = this.app.mongodb;
    const res = await db.collection(m).find().toArray();
    return res;
  }
  async getMovieDetailOrSearch(obj){
    const db = this.app.mongodb;
    const tables = ["top250","inTheaters","comingSoon"];
    const sum = [];
    for(var i=0;i<tables.length;i++){
      if(obj.id && obj.collected == 'undifined'){
        var {id} = obj;
        const res = await db.collection(tables[i]).find({ _id: id }).toArray();
        sum.push(...res);
        // if(obj.id && !obj.collected){
        //     var res = await db.collection(tables[i]).find({_id:obj.id}).toArray();
        //     sum.push(...res);
        }else if(obj.keyword){
            var keyword = new RegExp(obj.keyword);
            var res = await db.collection(tables[i]).find({title:keyword}).toArray();
            sum.push(...res);
           
        }else if(obj.id && obj.collected != 'undifined'){
          var {id,collected} =obj
          await db.collection(tables[i]).updateOne({_id:id},{$set:{collected:collected}});
          // await db.collection(tables[i]).updataOne({ _id:id}, { $set: {collected:collected } })
          var res=await db.collection(tables[i]).find({_id:id}).toArray();
          sum.push(...res);
        }      
    }
    return  sum;
  }
}

module.exports = MovieService;
